package mornd.test1.custom;

import mornd.test1.annotation.Token;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * @author: mornd
 * @dateTime: 2023/5/7 - 16:56
 * 自定义 token 注解解析器
 */

public class TokenArgumentResolver implements HandlerMethodArgumentResolver {

    /**
     * 是否支持某个参数
     * @param parameter 控制器方法上的参数
     * @return
     */
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        Token token = parameter.getParameterAnnotation(Token.class);
        return token != null;
    }

    /**
     * 解析参数
     * @param parameter 参数对象
     * @param mavContainer
     * @param webRequest 即封装了 request，也封装了 response
     * @param binderFactory
     * @return
     * @throws Exception
     */
    @Override
    public Object resolveArgument(MethodParameter parameter,
                                  ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest,
                                  WebDataBinderFactory binderFactory) throws Exception {
        return webRequest.getHeader("token");
    }
}
